package com.cq.controllers;

import com.cq.model.SysFile;
import com.cq.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * @author admin
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private SysFileService sysFileService;

    @RequestMapping("download/{id}")
    public void download(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        Map map = sysFileService.getInputStream(id);
        SysFile f = (SysFile) map.get("f");
        InputStream inputStream = (InputStream) map.get("s");
        response.setContentType("multipart/form-data");
        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String(f.getOriginName().getBytes("utf-8"), "iso-8859-1") + "." + f.getSuffixes());
        OutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, n);
        }
        inputStream.close();
        outputStream.close();
    }

    @ResponseBody
    @PostMapping("upload")
    public Map<String, Object> uploadPic(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "x_requested_with");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        SysFile resource = sysFileService.fileUpload(file);
        return sysFileService.trans(resource);
    }
}
